package com.vf.s.mvc.sys.service;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.vf.core.model.ZtreeNode;
import com.vf.core.render.RenderLayuiBean;
import com.vf.s.common.model.sys.SysOrg;

public class RoleService{
	
	protected final Log LOG = Log.getLog(getClass());

	public List<SysOrg> getMenusForUser() {
		return getChildrenAllTree("root",null);
	}

	public List<SysOrg> getChildrenAllTree(String pId, String userId) {
		List<SysOrg> list = getChildrenByPid(pId, userId);
		for (SysOrg o : list) {
			o.setChildren(getChildrenAllTree(o.getID(),userId));
		}
		return list;
	}
	
	/***
	 * 根据id 查询孩子
	 * @param id
	 * @return
	 */
	public List<SysOrg> getChildrenByPid(String id,String userid) {
		String sql = "SELECT * FROM SYS_ORG M WHERE M.PARENTID='" + id + "'   ";
		if(userid!=null && !StrKit.isBlank(userid)) {
			String authSql=" (SELECT B.MENUID FROM SYS_USER_ROLE A,SYS_ROLE_AUTH B WHERE A.USER_ID='"+userid+"' AND  A.ROLE_ID=B.ROLEID) ";
			sql = sql + " and m.id in  "+authSql+" ";
		}
		sql = sql + " ORDER BY M.SORT";
		return SysOrg.dao.find(sql);
	}

	public RenderLayuiBean listData(Controller menuController) {
		List<SysOrg> list=SysOrg.dao.find("SELECT T.*, (CASE  WHEN (SELECT COUNT(ID) AS COUNT FROM SYS_ORG WHERE PARENTID=T.ID)>0 THEN TRUE ELSE  FALSE END ) AS HAVECHILD   FROM SYS_ORG  T  ORDER BY T.SORT ASC");
		RenderLayuiBean renderBean=new RenderLayuiBean();
		renderBean.setCode(0);
		renderBean.setMsg("查询成功");
		renderBean.setData(list);
		renderBean.setCount(list.size());
		return renderBean ;
	}

	/***
	 * 菜单转成ZTreeNode
	 * @param olist 数据 open 是否展开所有 ifOnlyLeaf 是否只选叶子
	 * @return
	 */
	public List<ZtreeNode> toZTreeNode(List<SysOrg> olist, Boolean open, Boolean ifOnlyLeaf) {
		List<ZtreeNode> list = new ArrayList<ZtreeNode>();
		for (SysOrg o : olist) {
			ZtreeNode node = toZTreeNode(o);
			if (o.getChildren() != null && o.getChildren().size() > 0) {// 如果有孩子
				node.setChildren(toZTreeNode(o.getChildren(), open, ifOnlyLeaf));
				if (ifOnlyLeaf) {// 如果只选叶子
					node.setNocheck(true);
				}
				node.setIsParent(true);
			}
			node.setOpen(open);
			list.add(node);
		}
		return list;
	}
	
	public ZtreeNode toZTreeNode(SysOrg org) {
		ZtreeNode node = new ZtreeNode();
		node.setId(org.getID());
		node.setName(org.getNAME());
		node.setType(org.getTYPE());
		node.setParentId(org.getPARENTID());
		return node;
	}

}
